/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: TextClientExample.cpp,v 1.5 2009-08-27 14:12:35 morsko Exp $
 *
 * \file
 * \brief This is an example for using the Text interface client.
 * \author Matthieu Myrsky <matthieu.myrsky@tkk.fi>
 */
#include "TextClient.hpp"
#include <curses.h>
#include <math.h>
//*****************************************************************************
#define GIMI_CLIENT_API 20000
#include "gimi.h"
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
// Objects
static bool run = true;
static gimi::GIMI g;
static MaCI::Text::CTextClient textC(&g, 0);


//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
static int verbose = 1;
//*****************************************************************************
//*****************************************************************************
static void DoText()
{
  // Initialize Curses (After this point, don't use printf family calls!)
  initscr(); 
  cbreak(); 
  nonl();
  intrflush(stdscr, FALSE);
  keypad(stdscr, TRUE);
  scrollok(stdscr, TRUE);

  // After this point, we don't want dPrint to print to Screen, so we disable it.
  debugSetPrintLevel(0);
  debugSetLogLevel(10);
  unsigned int timeout = 1000;
  unsigned int timeout_tfs = 2000;
  int sequence = 0;
  int seqTextFromServer = 0;
  clear();
  printw("Welcome to Text client test program.\n\n");

  do {
    int value;
    printw("\nSelect Text Query:\n");
    printw("1 = Send text to server\n"
           "2 = Send 'Clear Text'-command \n"
           "3 = Get Text Reply event(timeout %d ms)\n"
           "4 = Get Text from server(timeout %d ms) \n"
           "q = QUIT\n", timeout,timeout_tfs);
    printw("?\n");
    value = getch();
    clear(); // After input, clear the screen. Not after processing!
    switch(value){
    case '1':{
      int maxChar = 1000;
      printw("Type text(%d characters) and press enter to send it\n",maxChar);
      char c[maxChar];
      getnstr(c,maxChar);
      std::string s(c);
      textC.SendText(s);
      
      break;
    }

    case '2':{
      if(textC.ClearText()){
        printw("Succesfully sent command!\n");
        
      }else{
        printw("Command sending FAILED!\n");
      }
      break;
    }
    case '3':{
      std::string text;
      if(textC.GetTextAccomplishedEvent(text,
                                        &sequence,
                                        timeout)){
        printw("Text server just accomplished following text '%s'\n", text.c_str());

      }else{
        printw("No event :(\n");
      }
      break;
    }

    case '4':{
      std::string text;
      if(textC.GetTextEvent(text,
                            &seqTextFromServer,
                            timeout_tfs)){
        printw("Text server just sent a text '%s'\n",text.c_str());

      }else{
        printw("No event :(\n");
      }
      break;
    }
    case 'q':{
      
      run = false;
      printw("\nBYE BYE!.\n\n");
      
      break;
    }
    default:{
      clear();
      printw("\nUnknown command.\n\n");
      continue;
      break;
    }
    }
    
  } while(run);
  
  // Close curses.
  endwin();
  
      
}
//*****************************************************************************
void showUsage()
{
  fprintf(stderr,"\n");
  fprintf(stderr,"Usage:\tJointGroupCtrlClientExample [OPTIONS]\n");
  fprintf(stderr,"  [-u addr]\t\t\tUse 'addr' as GIMnet AccessPoints address\n");
  fprintf(stderr,"  [-p port]\t\t\tUse 'port' as GIMnet AccessPoints port\n");
  fprintf(stderr,"  [-n name]\t\t\tUse 'name' as this nodes GIMnet name\n");
  fprintf(stderr,"  [-s name]\t\t\tUse 'name' as Text target\n");
  fprintf(stderr,"  \t\t\t\tOR\n"); 
  fprintf(stderr,"  [-v]\t\t\t\tIncrease verbosity by 1\n");
  fprintf(stderr,"  [-q]\t\t\t\tQuiet mode\n");
  fprintf(stderr, "\n\n");
}
//*****************************************************************************

int main(int argc, char *argv[]) {
  // GIMnet parameters
  std::string gimnetAP = "asrobo.hut.fi";
  int gimnetAPPort = 40002;
  std::string gimnetName = "";
  std::string gimnetSourceName = "";
  std::string datasourceMaCISL;
  // Init Debug lib
  debugInit();
  debugSetGlobalDebugLvl(8);
  debugSetLogFilename("TextClientExample.log");
  debugSetLogLevel(10);
  // Greet
  fprintf(stderr,
	  "\nTextClientExample - MaCI Text Interface Example - v0.0\n");

  // Parse parameters
  bool parse = true;
  while(parse) {
    int c;
    c = getopt(argc, argv, "s:S:n:u:p:hqv");
    switch(c) {

      /////////////////////////////////
      ////// Application specific /////
      /////////////////////////////////

      /////////////////////////////////
      ///// GIMnet parameters /////////
      /////////////////////////////////
    case 's':
      gimnetSourceName = optarg;
      dPrint(3,"Using GIMnet source name '%s'", optarg);
      break;

    case 'S':
      datasourceMaCISL = optarg;
      dPrint(3,"Using DataSource MaCISL '%s'", optarg);
      break;

    case 'n':
      gimnetName = optarg;
      dPrint(3,"Using GIMnet Name '%s'", optarg);
      break;

    case 'u':
      gimnetAP = optarg;
      dPrint(3,"Using GIMnetAP address '%s'", optarg);
      break;

    case 'p':
      gimnetAPPort = atoi(optarg);
      dPrint(3,"Using GIMnetAP port '%d'", gimnetAPPort);
      break;

      //////////////////////////////////
      //// GENERIC:                 ////
      //////////////////////////////////
    case 'v':
      // Increase only if not previously set to 0 (by 'quiet')
      if (verbose > 0)
	debugSetGlobalDebugLvl(++verbose);
      break;
      
    case 'q':
      verbose = 0;
      debugSetGlobalDebugLvl(0);
      break;
      
    case 'h':
    case '?':
      showUsage();
      exit(1);
      break;
      
    case -1:
      parse = false;
      break;
    }
  }


  MaCI::EMaCIError e;
  
  int r;
  if ( (r = g.connectToHubEx(gimnetAP, gimnetAPPort, gimnetName) ) != GIMI_OK) {
    dPrint(1,"Failed to connect to GIMnet AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());
    
  } else {
    dPrint(2,"Succesfully connected to GIMnet at AccessPoint '%s:%d' with name '%s': '%s'",
	   gimnetAP.c_str(), 
	   gimnetAPPort, 
	   gimnetName.size()?gimnetName.c_str():"<anonymous>",
	   gimi::getGimiErrorString(r).c_str());



    // Assign default target.
    if (gimnetSourceName.size()) {
      textC.SetDefaultTarget(gimnetSourceName);
      
    } else {
      // GIMI is Open(), so we can execute this.
      MaCI::MaCICtrl::SMaCISL sl(datasourceMaCISL);
      if (sl.IsValidFQMaCISL()) {
        textC.SetDefaultTarget(sl, 10000);
      }
    
    }
    // Attempt to Open Client
    if ( (e = textC.Open()) != MaCI::KMaCIOK) {
      dPrint(1,"Failed to Open TextClient instance! (%s)",
	     GetErrorStr(e).c_str());
      
    } else {

      DoText();
      textC.Close();
    }
  }
  
  return 0;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
